<?php
/**
 * Created by xun at 2020/5/8
 */

namespace app\module\websocket;

use app\base\DbPool;
use app\base\exception\Exception;
use app\base\MysqlConnection;
use app\base\Queue;
use app\storage\Config;
use app\storage\MysqlPool;
use app\storage\OnlineUser;
use app\storage\Singleton;
use huaweichenai\webSocket\WebSocketServer;

class Chatee extends WebSocketServer
{
    use Singleton;

    /**
     * @var bool
     * 开启自定义握手处理
     */
    public $handshake = true;

    public function __construct($host = null, $port = null, $config = [])
    {
        parent::__construct($host, $port, $config);
        \app\storage\MysqlPool::getInstance();
        \app\storage\OnlineUser::getInstance();
    }

    public function onStart($server)
    {
        parent::onStart($server);
        cli_set_process_title(Config::getConfig('process_name'));
        date_default_timezone_set('Asia/Shanghai');
    }

    /**
     * @param \swoole_websocket_server $server
     * @param \swoole_http_request $request
     *
     * 为用户分配身份并插入/更新到用户表。
     */
    public function handelSocketOpen($server, $request)
    {
        if (empty($request->get['is_reconnection']) || $request->get['is_reconnection'] == '0') {
            // todo 发送欢迎消息给用户
        }
    }

    /**
     * @param \swoole_websocket_server $server
     * @param \swoole_websocket_frame $frame
     *
     * 接收用戶消息json: {controller:'index', action: 'index', params: '{}'}
     * 分到對應控制器處理
     */
    public function handelSocketMessage($server, $frame)
    {
        try {
            $data = json_decode($frame->data, true);
            $controller = isset($data['controller']) ? $data['controller'] : 'index';
            $action = isset($data['action']) ? $data['action'] : 'index';
            $controller = 'app\controller\\' . ucfirst($controller) . 'Controller';
            if (class_exists($controller)) {
                $controller = new $controller([
                    'server' => $server,
                    'fd' => $frame->fd,
                    'data' => $data,
                ]);
                $controller->$action();
            }
        } catch (Exception $exception) {
            // todo
        }

    }

    /**
     * @param \swoole_websocket_server $server
     * @param $fd
     *
     * 用戶關閉連接之後，更新用戶為下綫狀態
     */
    public function handelSocketClose($server, $fd)
    {
        $table = OnlineUser::getInstance()->table();
        foreach ($table as $item) {
            if ($item['fd'] == $fd) {
                OnlineUser::getInstance()->table()->set($item['openid'], ['is_online' => 0]);
                // OnlineUser::getInstance()->set($key, ['is_online' => 0]);
                print_r("用户userid:{$item['username']}下线\n");
            }
        }
        // todo 通知對方 并推送消息到對方公衆號
    }

    /**
     * @param \swoole_websocket_server $server
     * 程序停止，清理所有内存（表）
     */
    public function handelSocketShutdown($server)
    {
        // $table = OnlineUser::getInstance()->table();
        // foreach ($table as $item) {
        //     OnlineUser::getInstance()->delete($item['fd']);
        // }
        // print_r('所有群清理完毕');
        MysqlPool::getInstance()->clear();
    }

}